export default {
  namespaced: true,
  state: {
    cartData: [],
  },
  getters: {
    total(state,payload){
      return state.cartData.reduce((total,item)=>{
        return total+=item.price*item.count
      },0)
    }
  },
  mutations: {
    SET(state, payload) {
      console.log(payload);
      let target = state.cartData.find(item =>item.id === payload.id);
      if (!target) {
        let obj = {
          title: payload.title,
          price: payload.price,
          id: payload.id,
          count: 1,
        };
        state.cartData.push(obj);
} else {
        target.count++;
      }
    },
    JIAN(state,payload){
      payload.count--
      let target = state.cartData.find(item =>item.id === payload.id);
      if (payload.count===0) {
        state.cartData = state.cartData.filter(item=>item.id!==payload.id)
      }
    }
  },
  actions: {
    SETCART(context, payload) {
      context.commit("SET", payload);
    },
    JIANJIAN(context,payload){
      context.commit('JIAN',payload)
    },
    JIAJIAJIA(context,payload){
      context.commit('products/JIA',payload,{root:true})
    }
  },
};
